import sys
import sqlite3
import hashlib
import logging

# 配置日志
logging.basicConfig(
    filename='app.log',
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
from PyQt6.QtWidgets import QApplication, QMessageBox, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton
from PyQt6.QtGui import QFont
from PyQt6.QtCore import Qt
from database import DB_NAME, create_user, create_database
from main_window import PyQtMainWindow


class LoginDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("小兔文档 - 登录")
        self.setFixedSize(300, 250)
        # 设置窗口图标
        import os
        from PyQt6.QtGui import QIcon
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.ico')
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        self.init_ui()


    def init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(15)


        # 标题
        title_label = QLabel("小兔文档")
        title_label.setFont(QFont("SimSun", 16, QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)


        # 用户名
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("用户名")
        layout.addWidget(self.username_edit)


        # 密码
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("密码")
        self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        layout.addWidget(self.password_edit)


        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.login)
        login_btn.setStyleSheet("padding: 8px;")
        layout.addWidget(login_btn)


        # 添加注册按钮
        register_btn = QPushButton("注册")
        register_btn.clicked.connect(self.open_register_dialog)
        register_btn.setStyleSheet("padding: 8px;")
        layout.addWidget(register_btn)


        self.setLayout(layout)


    def open_register_dialog(self):
        register_dialog = RegisterDialog()
        if register_dialog.exec() == QDialog.DialogCode.Accepted:
            # 注册成功后自动填充用户名
            self.username_edit.setText(register_dialog.username)
            self.password_edit.setFocus()


    def login(self):
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()


        if not username or not password:
            QMessageBox.warning(self, "提示", "请输入用户名和密码")
            return


        # 验证用户
        from database import verify_user
        user_id = verify_user(username, password)
        user = (user_id,) if user_id else None


        if user:
            self.accept()
            self.user_id = user[0]
        else:
            QMessageBox.critical(self, "错误", "用户名或密码错误")
            logging.error(f"登录失败: 用户名={username}")



class RegisterDialog(QDialog):  # 注册对话框类
    def __init__(self):
        super().__init__()
        self.username = ""
        self.setWindowTitle("小兔文档 - 注册")
        self.setFixedSize(300, 280)
        # 设置窗口图标
        import os
        from PyQt6.QtGui import QIcon
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.ico')
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        self.init_ui()


    def init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(12)


        # 标题
        title_label = QLabel("创建新账号")
        title_label.setFont(QFont("SimSun", 14, QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)


        # 用户名
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入用户名")
        layout.addWidget(self.username_edit)


        # 密码
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("请输入密码")
        self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        layout.addWidget(self.password_edit)


        # 确认密码
        self.confirm_edit = QLineEdit()
        self.confirm_edit.setPlaceholderText("请确认密码")
        self.confirm_edit.setEchoMode(QLineEdit.EchoMode.Password)
        layout.addWidget(self.confirm_edit)


        # 注册按钮
        register_btn = QPushButton("注册")
        register_btn.clicked.connect(self.register)
        register_btn.setStyleSheet("padding: 8px;")
        layout.addWidget(register_btn)


        self.setLayout(layout)


    def register(self):
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()
        confirm = self.confirm_edit.text().strip()


        # 输入验证
        if not username or not password or not confirm:
            QMessageBox.warning(self, "提示", "所有字段都不能为空")
            return
        if password != confirm:
            QMessageBox.warning(self, "提示", "两次输入的密码不一致")
            return
        if len(password) < 6:
            QMessageBox.warning(self, "提示", "密码长度不能少于6位")
            return


        # 调用数据库创建用户
        from database import create_user
        if create_user(username, password):
            self.username = username
            QMessageBox.information(self, "成功", "注册成功！请使用新账号登录")
            self.accept()
        else:
            QMessageBox.critical(self, "错误", "用户名已存在")


if __name__ == "__main__":
    logging.info("应用程序开始启动")
    # 确保数据库表结构存在
    create_database()
    logging.info("数据库表结构已确保存在")
    
    # 新增：更新数据库模式以添加新列
    from database import update_database_schema
    update_database_schema()
    logging.info("数据库模式已更新")
    
    app = QApplication(sys.argv)
    logging.info("创建登录对话框")
    login_dialog = LoginDialog()
    if login_dialog.exec() == QDialog.DialogCode.Accepted:
        logging.info(f"用户 {login_dialog.user_id} 登录成功")
        main_window = PyQtMainWindow(user_id=login_dialog.user_id)
        main_window.show()
        logging.info("主窗口已显示")
        sys.exit(app.exec())
    else:
        logging.info("用户取消登录")